package com.feihong.txgw.ui.activity.setting;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.AppUtils;
import com.dtr.settingview.lib.SettingView;
import com.dtr.settingview.lib.entity.SettingData;
import com.dtr.settingview.lib.entity.SettingViewItemData;
import com.dtr.settingview.lib.item.BasicItemViewH;
import com.feihong.txgw.R;
import com.feihong.txgw.http.Host;
import com.feihong.txgw.http.HttpTools;
import com.feihong.txgw.inter.contract.setting.ISettingContract;
import com.feihong.txgw.inter.contract.setting.ISettingContract.ISettingMainView;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.model.SerializableHashMap;
import com.feihong.txgw.tx_precenter.SettingMainPrecenter;
import com.feihong.txgw.ui.activity.base.WebViewActivity;
import com.feihong.txgw.ui.activity.user.MyDeliveryAdrActivity;
import com.feihong.txgw.ui.mvp.BaseMVPCompateActivity;
import com.feihong.txgw.ui.mvp.precenter.AbBasePrecenter;
import com.feihong.txgw.utils.CacheDataManger;
import com.feihong.txgw.utils.PreferenceTools;
import com.feihong.txgw.utils.ToastUtils;
import com.feihong.txgw.utils.UserLoginInfo;
import com.feihong.txgw.utils.greendao.GreenDaoOperateHelper;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;
import ezy.boost.update.IUpdateParser;
import ezy.boost.update.UpdateInfo;
import ezy.boost.update.UpdateManager;
import ezy.boost.update.UpdateUtil;

public class SettingActivity extends BaseMVPCompateActivity<ISettingContract.AbSettingMainPrecenter> implements ISettingMainView {


    @BindView(R.id.set_setview)
    SettingView setSetview;
    @BindView(R.id.btn_exitlog)
    TextView btnExitlog;
    private ImageView imageView;
    private SettingData mItemData = null;
    private SettingViewItemData mItemViewData = null;
    private List<SettingViewItemData> mListData = new ArrayList<SettingViewItemData>();

    @Override
    public void setTheme() {

    }

    @Override
    public int setLayoutID() {
        return R.layout.activity_setting;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        setPageTitle("设置");
        setBackButtonFinish();
        // settingview的点击事件
        setSetview.setOnSettingViewItemClickListener(new SettingView.onSettingViewItemClickListener() {
            @Override
            public void onItemClick(int index) {

                switch (index) {
                    case 0:
                   //     ToastUtils.showShort("关于");
//                        Intent intent = new Intent(SettingActivity.this, AboutActivity.class);
//                        startActivity(intent);
                        Intent intentAbout = new Intent();
                        HashMap<String,String> paramsAbout = new HashMap<String, String>();
                        paramsAbout.put("h_case","1");
//                        String signAbout = new TokenUtils().setSigen(paramsAbout);
//                        String str = Host.HTTP_HOME+"App/Message/get_help?"+signAbout;
//                        Log.i(TAG, "onItemClick: "+str);
//                        intentAbout.putExtra("intent_weburl", str);
                        SerializableHashMap serializableHashMapAbout = new SerializableHashMap();
                        serializableHashMapAbout.setMap(paramsAbout);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable(WebViewActivity.INTENT_PARAMS,serializableHashMapAbout);
                        bundle.putString(WebViewActivity.INTENT_WEBURL,Host.HTTP_HOME + "App/Message/get_help?");
                        bundle.putString(WebViewActivity.INTENT_TITLE,"关于我们");
//                        intentAbout.putExtra("params", str);
//                        intentAbout.putExtra("intent_title", "关于");
                        intentAbout.putExtras(bundle);
                        intentAbout.setClass(SettingActivity.this, WebViewActivity.class);
                        startActivity(intentAbout);
                        break;
                    case 1:
                        Intent intentHelp = new Intent();
                        HashMap<String,String> params = new HashMap<String, String>();
                        params.put("h_case","2");
                        SerializableHashMap serializableHashMapHelp = new SerializableHashMap();
                        serializableHashMapHelp.setMap(params);
                        Bundle bundleHelp = new Bundle();
                        bundleHelp.putSerializable(WebViewActivity.INTENT_PARAMS,serializableHashMapHelp);
                        bundleHelp.putString(WebViewActivity.INTENT_WEBURL, Host.HTTP_HOME + "App/Message/get_help?");
                        bundleHelp.putString(WebViewActivity.INTENT_TITLE, getResources().getString(R.string.login_help_title));
                        intentHelp.putExtras(bundleHelp);
                        intentHelp.setClass(SettingActivity.this, WebViewActivity.class);
                        startActivity(intentHelp);
                        break;
                    case 2:

                        // 设置默认更新接口地址与渠道
                        UpdateManager.create(SettingActivity.this).setParser(new IUpdateParser() {
                            @Override
                            public UpdateInfo parse(String source) throws Exception {
                                UpdateInfo updateInfo = null;
                                try {
                                    updateInfo = JSON.parseObject(source, UpdateInfo.class);
                                    updateInfo.isIgnorable = false;
                                } catch (Exception ex) {

                                }

                                return updateInfo;
                            }
                        }).setUrl(UpdateUtil.toCheckUrl(SettingActivity.this, HttpTools.UPDATE_APP, "Android"))
                                .setManual(true).setWifiOnly(false).check();
                        // 进入应用时查询更新
                        //  UpdateManager.checkManual(SettingActivity.this);


                        break;
                    case 3:
                        CacheDataManger.clearAllCache(SettingActivity.this);
                        try {
                            if (CacheDataManger.getTotalCacheSize(SettingActivity.this).startsWith("0")) {
                                setSetview.modifySubTitle("0KB", index);
                                ToastUtils.getInstance().showShortToast("清理缓存成功");
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                    case 4:

                       // ToastUtils.showShort("意见反馈");
                        Intent intent1 = new Intent(getActivity(), SuggestActivity.class);
                        startActivity(intent1);

                        break;
                    default:break;
                }
            }
        });

        //没有登录,退出登录不可见
        if (!UserLoginInfo.isUserLogin()) {
            btnExitlog.setVisibility(View.GONE);
        } else {
            btnExitlog.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void bindData() {
        mItemViewData = new SettingViewItemData();
        mItemData = new SettingData();
        mItemData.setTitle("关于");
        mItemData.setTitleSize(14);

        mItemViewData.setData(mItemData);
        mItemViewData.setItemView(new BasicItemViewH(getActivity()));
        mListData.add(mItemViewData);

        mItemViewData = new SettingViewItemData();
        mItemData = new SettingData();
        mItemData.setTitle("在线帮助");
        mItemData.setTitleSize(14);


        mItemViewData.setData(mItemData);
        mItemViewData.setItemView(new BasicItemViewH(getActivity()));
        mListData.add(mItemViewData);

        mItemViewData = new SettingViewItemData();
        mItemData = new SettingData();
        mItemData.setTitle("升级APP");

        mItemData.setTitleSize(14);
        mItemData.setSubTitleSize(12);
        try {
            mItemData.setSubTitle(AppUtils.getAppVersionName());
        } catch (Exception e) {
            e.printStackTrace();
        }


        mItemViewData.setData(mItemData);
        mItemViewData.setItemView(new BasicItemViewH(getActivity()));
        mListData.add(mItemViewData);

        mItemViewData = new SettingViewItemData();
        mItemData = new SettingData();
        mItemData.setTitle("清理缓存");
        mItemData.setTitleSize(14);
        mItemData.setSubTitleSize(12);
        try {
            mItemData.setSubTitle(CacheDataManger.getTotalCacheSize(SettingActivity.this));
        } catch (Exception e) {
            e.printStackTrace();
        }

        mItemViewData.setData(mItemData);
        mItemViewData.setItemView(new BasicItemViewH(getActivity()));
        mListData.add(mItemViewData);

        mItemViewData = new SettingViewItemData();
        mItemData = new SettingData();
        mItemData.setTitle("意见反馈");
        mItemData.setTitleSize(14);

        mItemViewData.setData(mItemData);
        mItemViewData.setItemView(new BasicItemViewH(getActivity()));
        mListData.add(mItemViewData);

        setSetview.setAdapter(mListData);

    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    @OnClick(R.id.btn_exitlog)
    public void onViewClicked(View view) {
        //弹出个确认框
        switch (view.getId()) {
            case R.id.btn_exitlog:
                showConfirmDialog(null, "确定退出登录?", "确定", "取消",
                        new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                sweetAlertDialog.cancel();
                                btnExitlog.setClickable(false);
                                mPresenter.logout();
                            }
                        });
                break;
            default:break;
        }
    }

    @Override
    public void logoutResult(String result) {
        try {
            if(activityIsDestory()){
                return;
            }
            JSONObject logOutJsonObject = new JSONObject(result);
            if("200".equals(logOutJsonObject.optString("code"))){
                UserLoginInfo.userExitLogin();
                // 退出登录时  将默认收货地址的缓存清空
                PreferenceTools.putString(MyDeliveryAdrActivity.DEFAULT_ADR_KEY, "");
                PreferenceTools.putString("ll_info_result","");
                //应该把我的->用户名称 还原
                LoginMessage loginMessage = new LoginMessage();
                loginMessage.setAction(LoginMessage.ACTION_EXIT);
                GreenDaoOperateHelper.delAll();
                EventBus.getDefault().post(loginMessage);
                UserLoginInfo.updateUserToken(logOutJsonObject.optString("data"));
                finish();
            }else {
                showSystemToast(logOutJsonObject.optString("msg"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void loadDataComplated() {
        if(activityIsDestory()){
            return;
        }
        btnExitlog.setClickable(true);
    }

    @Override
    public void loadDataError() {

        if(activityIsDestory()){
            return;
        }
        showSystemToast(getString(R.string.connect_service_error));
    }

    @NonNull
    @Override
    public AbBasePrecenter initPresenter() {
        return SettingMainPrecenter.create();
    }
}
